﻿using System.Security.Cryptography;
using System.Text;

namespace WSS.BLL.Utils
{
    /*
     * 本类功能：
     * Md5加密
     * 返回md5hash字符串
     * 返回兼容asp 的 md5的值
     * 16位为兼容asp加密类
     * 32位为.net正常加密类
     */

    public class MD5
    {
        /// <summary>
        /// 16位MD5加密方法,以前的DVBBS所使用
        /// </summary>
        /// <param name="str_source">待加密字串</param>
        /// <returns>加密后的字串</returns>
        public static string MD5Encrypt(string str_source)
        {
            return MD5Encrypt(str_source, 16);
        }

        /// <summary>
        /// MD5加密,和动网上的16/32位MD5加密结果相同
        /// </summary>
        /// <param name="str_source">待加密字串</param>
        /// <param name="length">16或32值之一,其它则采用.net默认MD5加密算法</param>
        /// <returns>加密后的字串</returns>
        public static string MD5Encrypt(string str_source, int length)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(str_source);
            byte[] hash_value = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(bytes);

            var sb = new StringBuilder();
            switch (length)
            {
                case 16:
                    for (int i = 4; i < 12; i++)
                        sb.Append(hash_value[i].ToString("x2"));
                    break;
                case 32:
                    for (int i = 0; i < 16; i++)
                    {
                        sb.Append(hash_value[i].ToString("x2"));
                    }
                    break;
                default:
                    for (int i = 0; i < hash_value.Length; i++)
                    {
                        sb.Append(hash_value[i].ToString("x2"));
                    }
                    break;
            }
            return sb.ToString();
        }
    }
}